<?php
namespace app\admin\business;

use think\Exception;
use app\common\lib\Str;
use think\facade\Cache;
use app\common\model\SuperUser as SuperUserModel;

class Login
{
    public static function login($super_user){
        try {
            $auths = '';
            // 如果不是root 用户 需要获取用户权限
            if ($super_user['id'] > 1) {
                // 该用户角色信息
                $super_user_model = new SuperUserModel();
                $role = $super_user_model->role()->where('status', 1)->find($super_user['role_id']);
                if (!$role) throw new Exception('未分配角色!');
                $auths = explode(',', $role['auths']);
            }
            // 生成一个票据
            $token = Str::getLoginToken($super_user['username']);
            $result = [
                'id'=>$super_user['id'],
                'username'=>$super_user['username'],
                'avatar'=>$super_user['avatar'],
                'token'=>$token,
                'auths'=> $auths // 拥有的权限ID
            ];
            // 存储登陆信息
            Cache::store('redis')->set($token, $super_user['username']);
            Cache::store('redis')->set($super_user['username'], $result);
            return $result;
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }
}